package io.lvdaxian.mybatis05.datasource.unpooled;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

/**
 * 无池化技术 的数据源
 *
 * @author lihh
 */
public class UnpooledDataSource implements DataSource {
  
  // 驱动 的ClassLoader
  private ClassLoader driverClassLoader;
  // 驱动 属性扩展 比如 配置编码集
  private Properties driverProperties;
  
  // 表示 注册的驱动 map 实现类
  private static final Map<String, Driver> registeredDrivers = new ConcurrentHashMap<>();
  // 驱动
  private String driver;
  private String username;
  private String password;
  // jdbc 连接地址
  private String url;
  
  private Boolean autoCommit;
  // 表示默认的事务级别
  private Integer defaultTransactionIsolationLevel;
  
  static {
    // 拿到已经注册的驱动
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    
    while (drivers.hasMoreElements()) {
      Driver driver = drivers.nextElement();
      // 注册驱动
      registeredDrivers.put(driver.getClass().getName(), driver);
    }
  }
  
  /**
   * 驱动代理
   */
  private static class DriverProxy implements Driver {
    
    private Driver driver;
    
    DriverProxy(Driver driver) {
      this.driver = driver;
    }
    
    @Override
    public Connection connect(String u, Properties p) throws SQLException {
      return this.driver.connect(u, p);
    }
    
    @Override
    public boolean acceptsURL(String u) throws SQLException {
      return this.driver.acceptsURL(u);
    }
    
    @Override
    public DriverPropertyInfo[] getPropertyInfo(String u, Properties p) throws SQLException {
      return this.driver.getPropertyInfo(u, p);
    }
    
    @Override
    public int getMajorVersion() {
      return this.driver.getMajorVersion();
    }
    
    @Override
    public int getMinorVersion() {
      return this.driver.getMinorVersion();
    }
    
    @Override
    public boolean jdbcCompliant() {
      return this.driver.jdbcCompliant();
    }
    
    @Override
    public Logger getParentLogger() {
      return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    }
  }
  
  /***
   * 从 这个方法中 初始化驱动
   *
   * @author lihh
   */
  private synchronized void initializerDriver() throws SQLException {
    if (registeredDrivers.containsKey(driver)) return;
    
    try {
      Class<?> clazz = Class.forName(driver, true, driverClassLoader);
      // 驱动的类实例
      Driver driverInstance = (Driver) clazz.newInstance();
      // 驱动管理 注册 驱动
      DriverManager.registerDriver(new DriverProxy(driverInstance));
      // 缓存 驱动
      registeredDrivers.put(driver, driverInstance);
    } catch (Exception e) {
      throw new SQLException("Error setting driver on UnpooledDataSource. Cause: " + e);
    }
  }
  
  /**
   * 重载方法 为了格式化 username 以及password
   *
   * @param username 账号
   * @param password 密码
   * @return 返回 connection 连接
   * @author lihh
   */
  private Connection doGetConnection(String username, String password) throws SQLException {
    Properties props = new Properties();
    
    if (null != driverProperties)
      props.putAll(driverProperties);
    if (null != username)
      props.setProperty("user", username);
    if (null != password)
      props.setProperty("password", password);
    
    return doGetConnection(props);
  }
  
  private Connection doGetConnection(Properties props) throws SQLException {
    initializerDriver();
    
    // 通过 url 以及 props 拿到连接
    Connection connection = DriverManager.getConnection(url, props);
    
    // 设置 事务级别 以及自动提交
    if (null != autoCommit && autoCommit != connection.getAutoCommit())
      connection.setAutoCommit(autoCommit);
    if (null != defaultTransactionIsolationLevel)
      connection.setTransactionIsolation(defaultTransactionIsolationLevel);
    
    return connection;
  }
  
  @Override
  public Connection getConnection() throws SQLException {
    return getConnection(username, password);
  }
  
  @Override
  public Connection getConnection(String username, String password) throws SQLException {
    return doGetConnection(username, password);
  }
  
  @Override
  public <T> T unwrap(Class<T> iface) throws SQLException {
    throw new SQLException(getClass().getName() + " is not a wrapper.");
  }
  
  @Override
  public boolean isWrapperFor(Class<?> iface) throws SQLException {
    return false;
  }
  
  @Override
  public PrintWriter getLogWriter() throws SQLException {
    return DriverManager.getLogWriter();
  }
  
  @Override
  public void setLogWriter(PrintWriter out) throws SQLException {
    DriverManager.setLogWriter(out);
  }
  
  @Override
  public void setLoginTimeout(int seconds) throws SQLException {
    DriverManager.setLoginTimeout(seconds);
  }
  
  @Override
  public int getLoginTimeout() throws SQLException {
    return DriverManager.getLoginTimeout();
  }
  
  @Override
  public Logger getParentLogger() throws SQLFeatureNotSupportedException {
    return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
  }
  
  public ClassLoader getDriverClassLoader() {
    return driverClassLoader;
  }
  
  public void setDriverClassLoader(ClassLoader driverClassLoader) {
    this.driverClassLoader = driverClassLoader;
  }
  
  public Properties getDriverProperties() {
    return driverProperties;
  }
  
  public void setDriverProperties(Properties driverProperties) {
    this.driverProperties = driverProperties;
  }
  
  public String getDriver() {
    return driver;
  }
  
  public void setDriver(String driver) {
    this.driver = driver;
  }
  
  public String getUsername() {
    return username;
  }
  
  public void setUsername(String username) {
    this.username = username;
  }
  
  public String getPassword() {
    return password;
  }
  
  public void setPassword(String password) {
    this.password = password;
  }
  
  public String getUrl() {
    return url;
  }
  
  public void setUrl(String url) {
    this.url = url;
  }
  
  public Boolean getAutoCommit() {
    return autoCommit;
  }
  
  public void setAutoCommit(Boolean autoCommit) {
    this.autoCommit = autoCommit;
  }
  
  public Integer getDefaultTransactionIsolationLevel() {
    return defaultTransactionIsolationLevel;
  }
  
  public void setDefaultTransactionIsolationLevel(Integer defaultTransactionIsolationLevel) {
    this.defaultTransactionIsolationLevel = defaultTransactionIsolationLevel;
  }
}
